package cn.gov.chinamor;

import java.io.IOException;
import java.util.Collection;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import cn.gov.chinamor.zxing.client.CameraManager;
import cn.gov.chinamor.zxing.om.BusDataModel;
import cn.gov.chinamor.zxing.util.CaptureActivityHandler;
import cn.gov.chinamor.zxing.util.DataEncoder;
import cn.gov.chinamor.zxing.util.InactivityTimer;
import cn.gov.chinamor.zxing.view.ViewfinderView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class CaptureActivity extends Activity implements SurfaceHolder.Callback {

	private CameraManager cameraManager;
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Collection<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Window window = getWindow();
	    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	    setContentView(R.layout.capture_window);

	    hasSurface = false;
	    inactivityTimer = new InactivityTimer(this);
	    
//	    Button back = (Button) findViewById(R.id.btnBack);
//	    back.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				CaptureActivity.this.finish();
//				overridePendingTransition(R.anim.left_to_right_in, R.anim.left_to_right_out);
//			}
//		});
	}
	
	@Override
    protected void onResume() {
        super.onResume();
        
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats =null;
        characterSet =null;
    }
	
	@Override
	protected void onPause() {
	    if (handler != null) {
	    	handler.quitSynchronously();
	    	handler = null;
	    }
	    inactivityTimer.onPause();
	    cameraManager.closeDriver();
	    if (!hasSurface) {
	    	SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
	    	SurfaceHolder surfaceHolder = surfaceView.getHolder();
	    	surfaceHolder.removeCallback(this);
	    }
	    super.onPause();
	}

	@Override
	protected void onDestroy() {
	    inactivityTimer.shutdown();
	    super.onDestroy();
	}
	
	 private void initCamera(SurfaceHolder surfaceHolder) {
		 try {
			 cameraManager.openDriver(surfaceHolder);
         } catch (IOException ioe) {
        	 return;
         } catch (RuntimeException e) {
        	 return;
         }
		 
		 if (handler ==null) {
             handler =new CaptureActivityHandler(this, decodeFormats, characterSet, cameraManager);
         }
     }
	 

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface =true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface =false;
    }

	public CameraManager getCameraManager() {
		return cameraManager;
	}

	public Handler getHandler() {
		return handler;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	/**
	   * A valid barcode has been found, so give an indication of success and show the results.
	   *
	   * @param rawResult The contents of the barcode.
	   * @param barcode   A greyscale bitmap of the camera data which was decoded.
	   */
	public void handleDecode(Result rawResult, Bitmap barcode) {
	    inactivityTimer.onActivity();
//	    lastResult = rawResult;
	    Log.v("handleDecode", rawResult.getText());
	    
		Intent intent = new Intent(CaptureActivity.this, ResultActivity.class);
		intent.putExtra("qrImage", barcode);
		String[] tmp = rawResult.getText().split(",");
		String oString = null;
		try {
			oString = DataEncoder.desDecrypt(tmp[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		if (oString == null) {
//			return;
//		}
		BusDataModel dm = BusDataModel.parseString(tmp[0] + "," + oString);
		intent.putExtra("busData", dm);
		startActivity(intent);
//		finish();
		overridePendingTransition(R.anim.right_to_left_in, R.anim.right_to_left_out);
	}
	  
	public void drawViewfinder() {
	    viewfinderView.drawViewfinder();
	}
}
